﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Xna.Framework.Graphics;

namespace client.app
{
    public sealed class RPackManager
    {
        public int AllTexCount { get { return _texDic.Count; } }

        Dictionary<string, comm.objst.RPack> _rpackDic = new Dictionary<string, comm.objst.RPack>();
        Dictionary<string, Texture2D> _texDic = new Dictionary<string, Texture2D>();

        public RPackManager()
        {
        }

        public Texture2D GetTexture(string texId)
        {
            Texture2D tex = null;
            _texDic.TryGetValue(texId, out tex);
            return tex;
        }
        public comm.objst.RPack LoadRPack(string rpackFile)
        {
            comm.objst.RPack rpack = null;
            lock (this)
            {
                if (_rpackDic.ContainsKey(rpackFile))
                {
                    rpack = _rpackDic[rpackFile];
                }
                if (rpack == null)
                {
                    #region read RPack file
                    rpack = comm.objst.RPack.FromFile(rpackFile.Replace("[ROOT]", MainGame.DefineFile.Folder));
                    foreach (var resKey in rpack.ResourceDic.Keys)
                    {
                        var res = rpack.ResourceDic[resKey];
                        if (res is comm.objst.RImage)
                        {
                            var rImage = (comm.objst.RImage)res;
                            var texId = comm.GUID.NewString();
                            using (var ms = new MemoryStream(rImage.ImageBytes))
                            {
                                var tex = Texture2D.FromStream(MainGame.Instance.GraphicsDevice, ms);
                                _texDic.Add(texId, tex);
                            }
                            rImage.ImageBytes = Encoding.UTF8.GetBytes(texId);
                        }
                    }
                    _rpackDic.Add(rpackFile, rpack);
                    #endregion
                }
            }
            return rpack;
        }
    }
}
